package com.gz.mylife.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.ref.WeakReference;

import org.json.JSONException;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.im.PhotoUtil;
import com.gz.mylife.im.PhotoUtil.CropOption;
import com.gz.mylife.util.ImageUtils;
import com.gz.mylife.util.PushUtils;
import com.gz.mylife.widget.GenderSelectButton;
import com.gz.mylife.widget.GenderSelectButton.SelectButtonListener;
import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.po.CookieInfo;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.account.vo.CookieInfoDao;
import com.zl.smartmall.library.account.vo.UserInfoDao;
import com.zl.smartmall.library.concurrent.ThreadExecutor;
import com.zl.smartmall.library.listener.PhoneRegisterListener;
import com.zl.smartmall.library.listener.RegisterCidListener;
import com.zl.smartmall.library.listener.RegisterTagListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.MD5;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Register3 extends BaseActivity implements OnClickListener {

	private static final String TAG = Register3.class.getSimpleName();
	private GenderSelectButton mSelectGender;
	private EditText mEtNickName;
	private ImageView mIvFace;
	private Dialog mLoadingData;

	private String smscode;
	private String phone;
	private String password;
	private int gender = -1;
	private String mFacePath;

	private PhotoUtil mPhotoUtil;
	private PhotoUtil.Config mFaceConfig;
	
	private MyPhoneRegisterListener mListener;
	private RegisterCidListener mRegisterCidListener;
	private RegisterTagListener mRegisterTagListener;
	
	private MyHandler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register3);
//		mActionBar.setTitle("完善资料");
		setActionbarTitle("完善资料", false);
		
		mListener = new MyPhoneRegisterListener(this);
		mHandler = new MyHandler(this);
		
		mSelectGender = (GenderSelectButton) findViewById(R.id.select_gender);
		
		mLoadingData = new Dialog(this, R.style.DialogTheme);
		View loadView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.loading_data_dialog2, null);
		mLoadingData.setContentView(loadView);
		TextView mTvLoading = (TextView) loadView.findViewById(R.id.show_tv);
		mTvLoading.setText("请求中...");
		mLoadingData.setCanceledOnTouchOutside(true);

		smscode = getIntent().getStringExtra("smscode");
		phone = getIntent().getStringExtra("phone");
		password = getIntent().getStringExtra("password");

		mEtNickName = (EditText) findViewById(R.id.et_nickname);
		mIvFace = (ImageView) findViewById(R.id.iv_face);
		mIvFace.setOnClickListener(this);
		mEtNickName.addTextChangedListener(nickNameWatcher);
		findViewById(R.id.btn_update).setOnClickListener(this);

		mPhotoUtil = new PhotoUtil(this);
		mFaceConfig = new PhotoUtil.Config().setIsCrop(true)
				.setIsReturnImage(true)
				.setCropOption(new CropOption(1, 1, 480, 480))
				.setPhotoCallback(faceCallback);
		
		mSelectGender.setListener(new SelectButtonListener() {
			
			@Override
			public void rightSelected() {
				gender = 2;
			}
			
			@Override
			public void leftSelected() {
				gender = 1;
			}
		});
		
		
		mRegisterCidListener = new RegisterCidListener() {

			int reqCount;
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				if(reqCount < 5) {//失败重试5次
					reqCount++;
					IAuth.getInstance().registerCID(PreferenceModel.getString(Define.PREFERENCE_KEY_CID, ""), this);
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "CID注册成功");
			}
		};
		
		mRegisterTagListener = new RegisterTagListener() {
			
			int reqCount;
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				if(reqCount < 5) {//失败重试5次
					reqCount++;
					IAuth.getInstance().registerTAG(PushUtils.buildTag(getApplicationContext()), mRegisterTagListener);
				}
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "TAG注册成功");
			}
		};

	}

	PhotoUtil.PhotoCallback faceCallback = new PhotoUtil.PhotoCallback() {
		@Override
		public void onBack(final Bitmap bitmap, final String path) {
			// uploadFace(new File(path));
			Bitmap bitmap2 = Tools.getFitBitmap(path,
					Tools.dip2px(getApplicationContext(), 61));
			mFacePath = path;
			Bitmap roundedCornerBitmap = ImageUtils.getRoundedCornerBitmap(
					bitmap2, Tools.dip2px(getApplicationContext(), 3));
			mIvFace.setImageBitmap(roundedCornerBitmap);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (mPhotoUtil != null) {
			mPhotoUtil.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mListener.release();
		mHandler.release();
	}

	private TextWatcher nickNameWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			if (TextUtils.isEmpty(s.toString())) {
				// mEtNickName.setCompoundDrawables(null, null,null, null);
				// if(saveItem != null){
				// saveItem.setVisible(false);
				// }
			} else {
				// Drawable rightDrawable =
				// getResources().getDrawable(R.drawable.ic_changenicknamesign_x);
				// rightDrawable.setBounds(0, 0,
				// rightDrawable.getIntrinsicWidth(),
				// rightDrawable.getIntrinsicHeight());
				// mEdit.setCompoundDrawables(null, null,rightDrawable, null);
				// if(saveItem != null){
				// saveItem.setVisible(true);
				// }
				String str = s.toString();
				if (str.length() > 12) {
					str = str.substring(0, 12);
					mEtNickName.setText(str);
					mEtNickName.setSelection(12);
				}

			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_update:
			if (TextUtils.isEmpty(mEtNickName.getText().toString().trim())) {
				Toast.makeText(this, "昵称不能为空或全部为空格", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if(gender == -1){
				Toast.makeText(this, "请选择您的性别", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (TextUtils.isEmpty(mFacePath)) {
				Toast.makeText(this, "请选择头像", Toast.LENGTH_SHORT).show();
				return;
			}
			mLoadingData.show();
			loadDataFromServer();
			
			break;
		case R.id.iv_face:
			InputMethodManager mInputMethod = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (mInputMethod.isActive()) {
				mInputMethod.hideSoftInputFromWindow(getCurrentFocus()
						.getApplicationWindowToken(), 0);
			}
			mPhotoUtil.takePhoto(mFaceConfig);
			break;

		default:
			break;
		}
	}
	
	private void loadDataFromServer(){
		if (!Tools.hasInternetConnection(getApplicationContext())) {
			mLoadingData.dismiss();
			Toast.makeText(this, Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		String url = Constants.URL_PHONE_REGISTER;
		RequestParams params = new RequestParams();
		
		final String imei =Tools.getIMEI(getApplicationContext());
		final String mac;
		String macAddress = Tools.getLocalMacAddress(getApplicationContext());
		if(TextUtils.isEmpty(macAddress)){
			mac = imei;
		} else {
			mac = macAddress;
		}
		final String alias =MD5.md5(imei+mac);
		final long localDatetime = System.currentTimeMillis()/1000;
		final String appver =Tools.getAppVersionName(getApplicationContext());
		String discuzId = "";
		
		//params.put("openId", openId);
		
//		mac		# 必填，本机的mac
//		imei		# 必填，本机的imei
		params.put("mac", mac);
		params.put("imei", imei);
		params.put("devicetime", localDatetime+"");
		params.put("alias", alias);
		
//		version 	# 选填，版本号
		params.put("appver", appver);
		
		params.put("discuz_id", discuzId);
		
		//bundleID	# 选填，字符串，包名的第三部分 如 "com.bulogame.tiantian" ,则 bundleID 为 "tiantian"
		params.put("bundleID", "");
		params.put("jutt", 1);  //0为uid，1为md5(uid_mac)
		
		//marketid 	# 选填，渠道号
		params.put("marketid", Tools.getChannelName(getApplicationContext()));	
		
		/*
		 * lng 		# 选填，经纬度信息
			lat 		# 选填，经纬度信息
			province 	# 选填，省份
			city 		# 选填，城市
			address		# 选填，地址
		 */
//		params.put("lat", PreferenceModel.getString(PreferenceModel.KEY_LATITUDE, ""));
//		params.put("lng", PreferenceModel.getString(PreferenceModel.KEY_LONGITUDE, ""));
//		params.put("province", PreferenceModel.getString(PreferenceModel.KEY_LOCATION_PROVINCE, ""));
//		params.put("city", PreferenceModel.getString(PreferenceModel.KEY_LOCATION_CITY, ""));
//		params.put("address", PreferenceModel.getString(PreferenceModel.KEY_LOCATION_ADDRESS, ""));
		/*
		 * phone		# 11位的手机号码
			smscode 	# 短信认证码
			password 	# 登录密码,md5之后的值
			nickname 	# 昵称
			gender 		# 选填，性别，0女性，1男性
			image 		# 头像的文件域
			*/
		params.put("phone", phone);
		params.put("smscode", smscode);
		params.put("password", password);
		params.put("nickname", mEtNickName.getText().toString());
		params.put("gender", gender+"");
		try {
			params.put("image", new File(mFacePath));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SingtonAsyncHttpClient.getInstance().post(url, params, mListener);
	}
	
	
	
	private static class MyPhoneRegisterListener extends PhoneRegisterListener{
		protected Register3 mOuter;
		
		public MyPhoneRegisterListener(Register3 outer){
			this.mOuter = outer;
		}
		
		public void release(){
			new WeakReference<Register3>(mOuter);
		}

		@Override
		public void onResponseSuccess(CookieInfo cookieInfo,UserInfo userinfo) {
//			UserinfoDao.save(mOuter.getApplicationContext(), userinfo);
//			Global.get().getUserinfo(true);
//			Intent exit = new Intent(Define.ACTION_APP_EXIT);
//			mOuter.sendBroadcast(exit);
//			//startActivity(new Intent(Login.this, MainTab.class));
//			mOuter.startActivity(new Intent(mOuter, Plaza.class));
			
			if(mOuter == null){
				return;
			}
			mOuter.saveToDB(cookieInfo, userinfo);
			
		}

		@Override
		public void onSmsCodeError() {
			if(mOuter == null){
				return;
			}
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "验证码输入有误", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onResponseFailed() {
			if(mOuter == null){
				return;
			}
			// TODO Auto-generated method stub
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show();
		}


		@Override
		public void onNoNetWork() {
			// TODO Auto-generated method stub
			
		}
		
		
	}
	
	private void saveToDB(final CookieInfo cookieInfo,final UserInfo userInfo){
		ThreadExecutor.getInstance().execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//存储cookie
					if(cookieInfo != null) {
						CookieInfoDao cookieInfoDao = new CookieInfoDao(getApplicationContext());
						cookieInfoDao.delete();
						cookieInfoDao.insert(cookieInfo);
					}
					
					PreferenceModel.putInt(Constants.PREFERENCE_KEY_UID, userInfo.getUid());
//					PreferenceModel.putString(Constants.PREFERENCE_KEY_TOKEN, userInfo.getToken());
					PreferenceModel.putString(Constants.PREFERENCE_KEY_LOGIN_PLATFORM, userInfo.getLoginPlatform());
					UserInfoDao userInfoDao = new UserInfoDao(getApplicationContext());
					userInfoDao.delete();
					userInfoDao.insert(userInfo);
					mHandler.sendEmptyMessage(1);
					
					
				} catch (JSONException e) {
					CrashHandler.e(e);
				}
			}
		});
	}
	
	private static class MyHandler extends Handler{
		private Register3 mOuter;
		
		public MyHandler(Register3 outer){
			this.mOuter = outer;
		}
		public void release(){
			new WeakReference<Register3>(mOuter);
		}
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				UserInfo userinfo = IAuth.getInstance().loadUserInfo();
				if(userinfo != null) {
					IAuth.getInstance().registerCID(PreferenceModel.getString(Define.PREFERENCE_KEY_CID, ""), mOuter.mRegisterCidListener);
					IAuth.getInstance().registerTAG(PushUtils.buildTag(mOuter.getApplicationContext()), mOuter.mRegisterTagListener);
					Intent exit = new Intent(Define.ACTION_EXIT_WHOLE_APP);
					mOuter.sendBroadcast(exit);
//					//startActivity(new Intent(Login.this, MainTab.class));
					mOuter.startActivity(new Intent(mOuter.getApplicationContext(), Plaza.class));
					mOuter.mLoadingData.dismiss();
				}
				break;

			default:
				break;
			}
		}
	}
}

